<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>无限重复加载问题修复测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        .test-section {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .code {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 3px;
            padding: 10px;
            font-family: 'Courier New', monospace;
            overflow-x: auto;
            white-space: pre-wrap;
            word-break: break-all;
            font-size: 12px;
            max-height: 300px;
            overflow-y: auto;
        }
        .btn {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        .btn:hover {
            background: #0056b3;
        }
        .btn.danger {
            background: #dc3545;
        }
        .btn.danger:hover {
            background: #c82333;
        }
        .success {
            color: #155724;
            background: #d4edda;
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .error {
            color: #721c24;
            background: #f8d7da;
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .warning {
            color: #856404;
            background: #fff3cd;
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .info {
            color: #0c5460;
            background: #d1ecf1;
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .log-entry {
            font-family: monospace;
            font-size: 12px;
            padding: 2px 0;
            border-bottom: 1px solid #eee;
        }
        .log-popup { color: #007bff; }
        .log-background { color: #28a745; }
        .log-error { color: #dc3545; }
        .log-warning { color: #ffc107; }
    </style>
</head>
<body>
    <h1>🔧 无限重复加载问题修复测试</h1>

    <div class="test-section warning">
        <h2>⚠️ 问题描述</h2>
        <p><strong>原始问题：</strong> 插件显示"一直在加载"状态，按钮无法点击，UI不断重新渲染</p>
        <p><strong>根本原因：</strong> 重复流检测逻辑有缺陷，导致频繁的UI更新和消息通知</p>
    </div>

    <div class="test-section success">
        <h2>✅ 修复方案</h2>
        <h3>1. 防抖机制</h3>
        <div class="code">
// 添加防抖定时器，避免频繁处理
if (this.newStreamTimeout) {
  clearTimeout(this.newStreamTimeout);
}
this.newStreamTimeout = setTimeout(() => {
  this.processNewStream(streamData);
}, 100);
        </div>

        <h3>2. 防重复渲染</h3>
        <div class="code">
// 防止同时进行多次渲染
if (this.isRendering) {
  console.log('[Popup] Already rendering, skipping...');
  return;
}
        </div>

        <h3>3. 智能通知机制</h3>
        <div class="code">
// 只有真正的新流才发送通知
const isNewStream = await this.saveStreamData(streamData);
this.notifyPopupUpdate(streamData, isNewStream);
        </div>
    </div>

    <div class="test-section">
        <h2>🧪 测试功能</h2>
        <div id="testResults"></div>

        <button class="btn" onclick="startLoadingTest()">开始加载测试</button>
        <button class="btn" onclick="simulateDuplicateStreams()">模拟重复流</button>
        <button class="btn" onclick="testRenderPerformance()">测试渲染性能</button>
        <button class="btn danger" onclick="clearPluginData()">清除插件数据</button>
        <button class="btn" onclick="clearResults()">清除测试结果</button>
    </div>

    <div class="test-section">
        <h2>📊 实时日志监控</h2>
        <div id="logContainer" style="height: 300px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; background: #f8f9fa;">
            <div class="info">等待日志输出...</div>
        </div>
        <button class="btn" onclick="clearLogs()">清除日志</button>
    </div>

    <div class="test-section">
        <h2>📋 测试步骤</h2>
        <ol>
            <li><strong>重新加载插件</strong> - 在 chrome://extensions/ 中刷新插件</li>
            <li><strong>打开开发者工具</strong> - 按 F12，查看 Console 标签</li>
            <li><strong>访问目标页面</strong> - 打开华为云直播页面</li>
            <li><strong>观察加载状态</strong> - 插件应该正常加载，不会无限循环</li>
            <li><strong>测试按钮功能</strong> - 下载、复制、清除按钮应该正常可点击</li>
            <li><strong>检查控制台日志</strong> - 查看防抖和去重逻辑是否正常工作</li>
        </ol>
    </div>

    <script>
        const testResults = document.getElementById('testResults');
        const logContainer = document.getElementById('logContainer');

        let logCount = 0;
        let loadingTestActive = false;

        // 显示测试结果
        function showResult(message, type = 'info') {
            const result = document.createElement('div');
            result.className = type;
            result.innerHTML = message;
            testResults.appendChild(result);
        }

        // 显示日志
        function showLog(message, type = 'info') {
            logCount++;
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry log-${type}`;
            logEntry.innerHTML = `<strong>${logCount}.</strong> [${new Date().toLocaleTimeString()}] ${message}`;
            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
        }

        function clearResults() {
            testResults.innerHTML = '';
        }

        function clearLogs() {
            logContainer.innerHTML = '<div class="info">等待日志输出...</div>';
            logCount = 0;
        }

        // 拦截 console.log 来显示日志
        const originalLog = console.log;
        const originalError = console.error;
        const originalWarn = console.warn;

        console.log = function(...args) {
            originalLog.apply(console, args);
            const message = args.join(' ');
            if (message.includes('[Popup]') || message.includes('[Vhall]')) {
                const type = message.includes('[Popup]') ? 'popup' : 'background';
                showLog(message, type);
            }
        };

        console.error = function(...args) {
            originalError.apply(console, args);
            const message = args.join(' ');
            if (message.includes('[Popup]') || message.includes('[Vhall]')) {
                showLog(message, 'error');
            }
        };

        console.warn = function(...args) {
            originalWarn.apply(console, args);
            const message = args.join(' ');
            if (message.includes('[Popup]') || message.includes('[Vhall]')) {
                showLog(message, 'warning');
            }
        };

        // 测试功能
        async function startLoadingTest() {
            if (loadingTestActive) {
                showResult('⚠️ 加载测试已在进行中', 'warning');
                return;
            }

            loadingTestActive = true;
            showResult('🧪 开始加载测试...', 'info');

            try {
                if (typeof chrome !== 'undefined' && chrome.runtime) {
                    showLog('测试 Chrome 扩展连接...', 'info');

                    // 测试获取流数据
                    chrome.runtime.sendMessage({
                        type: 'GET_DETECTED_STREAMS'
                    }, function(response) {
                        if (chrome.runtime.lastError) {
                            showResult(`❌ 扩展通信失败: ${chrome.runtime.lastError.message}`, 'error');
                        } else {
                            showResult(`✅ 扩展通信正常，检测到 ${response.data ? response.data.length : 0} 个流`, 'success');
                            showLog(`获取到流数据: ${JSON.stringify(response, null, 2)}`, 'popup');
                        }
                        loadingTestActive = false;
                    });
                } else {
                    showResult('❌ Chrome API 不可用', 'error');
                    loadingTestActive = false;
                }
            } catch (error) {
                showResult(`❌ 测试失败: ${error.message}`, 'error');
                loadingTestActive = false;
            }
        }

        async function simulateDuplicateStreams() {
            showResult('🧪 模拟重复流测试...', 'info');

            if (typeof chrome !== 'undefined' && chrome.runtime) {
                // 发送多个相同的测试数据
                const testData = {
                    token: 'TEST_TOKEN_123',
                    referer: 'https://bbs.huaweicloud.com/live/cloud_live/202509051500.html',
                    page_url: 'https://bbs.huaweicloud.com/live/cloud_live/202509051500.html',
                    video_title: '测试视频标题',
                    detected_at: new Date().toISOString()
                };

                for (let i = 0; i < 5; i++) {
                    setTimeout(() => {
                        chrome.runtime.sendMessage({
                            type: 'TEST_STREAM_PROCESSING',
                            apiResponse: {
                                code: 200,
                                data: testData
                            },
                            requestInfo: {
                                referer: testData.referer,
                                tabId: 1
                            }
                        }, function(response) {
                            if (chrome.runtime.lastError) {
                                showLog(`测试 ${i + 1} 失败: ${chrome.runtime.lastError.message}`, 'error');
                            } else {
                                showLog(`测试 ${i + 1} 成功: ${JSON.stringify(response)}`, 'background');
                            }
                        });
                    }, i * 200); // 每200ms发送一次
                }

                showResult('📤 已发送5个重复测试数据，观察去重效果', 'info');
            } else {
                showResult('❌ Chrome API 不可用', 'error');
            }
        }

        function testRenderPerformance() {
            showResult('🧪 测试渲染性能...', 'info');

            if (typeof chrome !== 'undefined' && chrome.runtime) {
                const startTime = performance.now();

                chrome.runtime.sendMessage({
                    type: 'GET_DETECTED_STREAMS'
                }, function(response) {
                    const endTime = performance.now();
                    const duration = endTime - startTime;

                    if (chrome.runtime.lastError) {
                        showResult(`❌ 渲染测试失败: ${chrome.runtime.lastError.message}`, 'error');
                    } else {
                        showResult(`✅ 渲染测试完成，耗时: ${duration.toFixed(2)}ms，流数量: ${response.data ? response.data.length : 0}`, 'success');

                        if (duration > 100) {
                            showResult('⚠️ 渲染时间较长，可能存在性能问题', 'warning');
                        }
                    }
                });
            } else {
                showResult('❌ Chrome API 不可用', 'error');
            }
        }

        function clearPluginData() {
            showResult('🧹 清除插件数据...', 'info');

            if (typeof chrome !== 'undefined' && chrome.runtime) {
                chrome.runtime.sendMessage({
                    type: 'CLEAR_DETECTED_STREAMS'
                }, function(response) {
                    if (chrome.runtime.lastError) {
                        showResult(`❌ 清除失败: ${chrome.runtime.lastError.message}`, 'error');
                    } else {
                        showResult('✅ 插件数据已清除', 'success');
                        showLog('插件数据清除成功', 'popup');
                    }
                });
            } else {
                showResult('❌ Chrome API 不可用', 'error');
            }
        }

        // 页面加载时的初始化
        window.addEventListener('load', function() {
            showResult('🔧 无限重复加载问题修复测试工具已加载', 'success');
            showResult('点击上方按钮开始测试各项修复功能', 'info');
            showLog('测试工具已准备就绪，开始监控插件日志...', 'info');
        });

        // 页面卸载时清理
        window.addEventListener('beforeunload', function() {
            // 恢复原始 console 函数
            console.log = originalLog;
            console.error = originalError;
            console.warn = originalWarn;
        });
    </script>
</body>
</html>